package org.example.leetcode.core.filter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.leetcode.common.domain.SysUser;
import org.example.leetcode.common.exception.UnAuthorizationException;
import org.example.leetcode.common.utils.TokenUtils;
import org.example.leetcode.common.utils.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserInfoInterception implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String token = request.getHeader("Authorization");
        try{
            JSONObject jsonObjectFromToken = TokenUtils.getJsonObjectFromToken(token);
            SysUser sysUser = JSONUtil.toBean(jsonObjectFromToken, SysUser.class);
            UserInfo.setUserInfo(sysUser);
        }
        catch (Exception e){
            log.info("用户信息获取失败");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfo.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
